import { Component, Injector} from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LayoutElement } from './layout-element';
import { LayoutEditorHelper } from './layout-editor-helper';

@Component({
    templateUrl: './heading-editor-modal.component.html'
})
export class HeadingEditorModalComponent extends AppComponentBase {

    callback: ()=>void;
    item:LayoutElement;

    data: string = '';
    saving = false;
    heading: string = '';

    constructor(
        public bsModalRef: BsModalRef,
        injector: Injector
    ) {
        super(injector);
    }


    shown(item: LayoutElement) {
        this.item = item;
        try{
            let json = LayoutEditorHelper.headingDataToJson(item);
            this.heading = json.h;
            this.data = json.data;
        }catch{
            this.data = '';
            this.heading = '3';
        }
    }

    close(): void {
        this.bsModalRef.hide();
    }

    save() {
        if(this.item){
            this.saving = true;
            this.item.setItemData(this.getData());
            this.item.setItemHtml();
            this.saving = false;
            this.callback();
        }
        this.close();
    }

    private getData(): string{
        return JSON.stringify({h: this.heading, data: this.data});
    }
}
